<!-- 编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="'70%'"
    :model-value="modelValue"
    title="添加文章信息"
    @update:modelValue="updateModelValue"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent=""
    >

      <ele-tabs
        v-model="tabsActive"
        :items="[
            { name: '0', label: '内容' },
            { name: '1', label: '其它' }
        ]">
        <template #0>
          <div style="padding-top: 30px;">
            <el-row>
              <el-col>
                <el-form-item label="标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入标题" style="width: 100%;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="19">
                <el-form-item label="分类" prop="typeIds">
                  <el-select v-model="form.typeIds" multiple placeholder="请选择" style="width: 100%;" filterable
                             clearable>
                    <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.typeName"
                               :value="item.typeId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="置顶">
                  <el-checkbox true-value="1" false-value="0" v-model="form.top"></el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="内容">
              <el-row>
                <el-col>
                  <wang-editor v-model="form.content"></wang-editor>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </template>
        <template #1>
          <div style="padding-top: 30px;">
            <el-row>
              <el-col :span="8">
                <el-form-item label="首图">
                  <el-radio-group v-model="form.articlePicType">
                    <el-radio-button value="0">地址</el-radio-button>
                    <el-radio-button value="1">上传</el-radio-button>
                  </el-radio-group>
                  <div v-show="form.articlePicType === '0'" class="tabBlock">
                    <el-input v-model="form.articlePicLink" placeholder="请输入图片地址 https://"
                              style="margin-bottom: 10px;"/>
                    <el-image v-if="form.articlePicLink" :src="form.articlePicLink"
                              :preview-src-list="[form.articlePicLink]" fit="cover"
                              class="articlePic">
                    </el-image>
                    <img v-if="!form.articlePicLink"
                         src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt=""
                         slot="placeholder" fit="cover" class="articlePic"/>
                  </div>
                  <div v-show="form.articlePicType === '1'" class="tabBlock">
                    <image-upload
                      :limit="1"
                      v-model="form.articlePic"
                      :item-style="{ width: '260px', height: '117px', margin: 0 }"
                      :button-style="{ width: '260px', height: '117px', margin: 0 }"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="简介">
                  <el-input type="textarea" v-model="form.articleDesc" :autosize="{ minRows: 7, maxRows: 7}"
                            maxlength="50"
                            show-word-limit placeholder="请输入简介"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="跳转Url" prop="articleUrl">
                  <el-input
                    type="text"
                    v-model="form.articleUrl"
                    placeholder="此处填写需要跳转url，点击该文章列表会直接跳转该链接"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="发布时间" prop="createTime">
                <el-date-picker
                  v-model="form.createTime"
                  type="date"
                  placeholder="请选择发布时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:MM:ss"
                />
              </el-form-item>
            </el-row>
          </div>
        </template>
      </ele-tabs>
    </el-form>
    <template #footer>
      <!--      <el-button @click="updateModelValue(false)">取消</el-button>-->
      <!--      <el-button type="primary" :loading="loading" @click="save">-->
      <!--        保存-->
      <!--      </el-button>-->
      <el-button type="primary" @click="releaseForm" :loading="loading">发 布</el-button>
      <el-button type="info" @click="saveForm" :loading="loading">暂 存</el-button>
      <el-button @click="cancle">取 消</el-button>
    </template>
  </ele-modal>
</template>
<script setup>
import {ref, reactive, watch} from 'vue';
import {EleMessage} from 'ele-admin-plus/es';
import {useFormData} from '@/utils/use-form-data';
import {addArticle} from '@/api/cms/article';
import {ElMessageBox} from "element-plus";
import WangEditor from '@/views/cms/components/WangEditor/index.vue';
import ImageUpload from '@/views/cms/components/ImageUpload/index.vue';
import dayjs from 'dayjs';

const emit = defineEmits(['done', 'update:modelValue']);

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
  typeOptions: Array
});

/** 提交状态 */
const loading = ref(false);

/** 表单实例 */
const formRef = ref(null);


// const top = ref(null);


const tabsActive = ref('0');


/** 表单数据 */
const [form, resetFields, assignFields] = useFormData({
  id: void 0,
  createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  updateBy: '',
  updateTime: '',
  title: '',
  type: '', //这个字段废弃
  contentType: '0', //这个属性不再使用
  content: '',
  contentMarkdown: '',
  top: '0',
  views: void 0,
  status: '',
  articlePicType: '0',
  articlePic: '',
  articlePicLink: '',
  articleDesc: '',
  articleFiles: '',
  articleUrl: '',
  typeIds: [],
});

/** 表单验证规则 */
const rules = reactive({
  title: [
    {
      required: true,
      message: '请输入文章标题',
      type: 'string',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择所属分类',
      type: 'string',
      trigger: 'change'
    }
  ],
  typeIds: [
    {
      required: true,
      message: '请至少选择一个分类',
      trigger: 'blur'
    }
  ]
});


const releaseForm = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return;
    }
    ElMessageBox.confirm(
      `是否确认发布`,
      '系统提示'
    )
      .then(() => {
        // const loading = EleMessage.loading('请求中..');
        loading.value = true;
        form.type = 1;//文章分类，固定
        form.status = 1;
        addArticle(form).then(res => {
          loading.value = false;
          EleMessage.success(res);
          updateModelValue(false);
          emit('done');
        });
      })
      .catch((e) => {
        loading.value = false;
        EleMessage.error(e.message);
      });
  });
}

/** 更新modelValue */
const updateModelValue = (value) => {
  emit('update:modelValue', value);
};


const saveForm = () => {
  formRef.value?.validate?.((valid) => {
    if (!valid) {
      return;
    }
    ElMessageBox.confirm(
      `是否确认暂存`,
      '系统提示'
    )
      .then(() => {
        loading.value = true;
        form.type = 1;//文章分类，固定
        form.status = 0;
        addArticle(form).then(res => {
          // TODO 下面代码应该有用
          // if (this.fileIds.length > 0) {
          //   let fileBlogInfo = {
          //     articleId: response.data,
          //     fileIds: this.fileIds
          //   };
          //   addFileBlogInfo(fileBlogInfo).then(response => {
          //   });
          // }
          loading.value = false;
          EleMessage.success(res);
          updateModelValue(false);
          emit('done');
        });
      })
      .catch((e) => {
        loading.value = false;
        // EleMessage.error(e.message);
      });
  });
}

const cancle = () => {
  resetFields();
  updateModelValue(false);
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      // if (props.data) {
      //   assignFields(props.data);
      //   isUpdate.value = true;
      // } else {
      //   isUpdate.value = false;
      // }
    } else {
      resetFields();
      formRef.value?.clearValidate?.();
    }
  }
);
</script>

<style scoped lang="scss">
.tabBlock {
  height: 180px;
  margin-top: 10px;
}

.articlePic {
  height: 70px;
}
</style>
